package com.agent.common.utils;

import com.agent.common.constant.CommonConstants;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

/**
 * 文件操作工具类
 */
public class FileUtils {

    /**
     * 保存上传文件到指定目录
     * @param file 上传的文件
     * @param userId 用户ID
     * @param basePath 基础存储路径
     * @return 文件存储路径
     * @throws IOException 文件操作异常
     */
    public static String saveUploadedFile(MultipartFile file, Long userId, String basePath) throws IOException {
        // 验证文件大小
        if (file.getSize() > CommonConstants.MAX_FILE_SIZE) {
            throw new IllegalArgumentException("File size exceeds limit: " + CommonConstants.MAX_FILE_SIZE);
        }

        // 验证文件类型
        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null) {
            throw new IllegalArgumentException("Invalid file name");
        }

        String fileExtension = getFileExtension(originalFilename).toUpperCase();
        boolean supported = false;
        for (String type : CommonConstants.SUPPORTED_IMAGE_TYPES) {
            if (type.equals(fileExtension)) {
                supported = true;
                break;
            }
        }

        if (!supported) {
            throw new IllegalArgumentException("Unsupported file type: " + fileExtension);
        }

        // 生成存储路径
        String dateDir = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        String fileName = UUID.randomUUID() + "." + fileExtension;
        Path directory = Paths.get(basePath, "CreateAlVideo", userId.toString(), dateDir);
        
        // 创建目录（如果不存在）
        if (!Files.exists(directory)) {
            Files.createDirectories(directory);
        }
        
        // 保存文件
        Path filePath = directory.resolve(fileName);
        Files.copy(file.getInputStream(), filePath);
        
        // 返回相对路径
        return "CreateAlVideo" + CommonConstants.PATH_SEPARATOR + 
               userId + CommonConstants.PATH_SEPARATOR + 
               dateDir + CommonConstants.PATH_SEPARATOR + 
               fileName;
    }

    public static String getFileExtension(String filename) {
        int dotIndex = filename.lastIndexOf('.');
        if (dotIndex > 0 && dotIndex < filename.length() - 1) {
            return filename.substring(dotIndex + 1);
        }
        return "";
    }
}